package com.taojiazheng.common;

import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * @author 赵成林
 * @date 2017/11/23 17:19
 * 用来处理图片上传的操作
 * 返回一个图片保存的地址
 * 放在当前项目下
 */
@Component
public class UpLoadFile {
    /**
     *上传文件
     * todo 需要联调测试
     */
    public String uploadFile(MultipartFile file, HttpServletRequest re){
        String path = re.getSession().getServletContext().getRealPath("images");
        String fileName=file.getOriginalFilename();
        System.out.println(fileName);
        if(file == null){
            throw new ApplicationException(205,"文件出错");
        }
        String newFileName = new Date().getTime()+fileName.substring(fileName.indexOf('.'));
        File targetFile = new File(path,newFileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        try {
            file.transferTo(targetFile);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ApplicationException(205,"文件上传失败");
        }
        //String url = path+"/"+newFileName;
        String url = re.getContextPath()+"/images/"+ newFileName;
        System.out.println(url);
        return url;
    }
}
